package com.promise.jokerdream.task.base

import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import java.util.UUID
import java.util.concurrent.atomic.AtomicInteger

/**
 * 任务抽象基类
 */
abstract class BaseTask(
    override val name: String,
    override val taskType: TaskType,
    override val totalRepeatCount: Int = 1
) : ITask {

    override val id: String = UUID.randomUUID().toString()

    private var _status: TaskStatus = TaskStatus.PENDING
    private var _job: Job? = null
    private val _currentExecutionCount = AtomicInteger(0)

    override val currentExecutionCount: Int
        get() = _currentExecutionCount.get()

    override val isCompleted: Boolean
        get() = _currentExecutionCount.get() >= totalRepeatCount && _status != TaskStatus.RUNNING

    override fun getStatus(): TaskStatus = _status

    override suspend fun execute(): TaskResult {
        if (_status == TaskStatus.RUNNING) {
            return TaskResult.Failure(IllegalStateException("任务已在运行中"))
        }

        if (_status == TaskStatus.CANCELLED) {
            return TaskResult.Cancelled
        }

        return try {
            _status = TaskStatus.RUNNING

            // 执行重复任务
            val results = mutableListOf<TaskResult>()

            while (!isCompleted && _status == TaskStatus.RUNNING) {
                // 执行单次任务
                val singleResult = doExecute()
                results.add(singleResult)
                _currentExecutionCount.incrementAndGet()

                // 检查单次执行结果
                when (singleResult) {
                    is TaskResult.Failure -> {
                        _status = TaskStatus.FAILED
                        return TaskResult.Failure(singleResult.error)
                    }
                    is TaskResult.Cancelled -> {
                        _status = TaskStatus.CANCELLED
                        return TaskResult.Cancelled
                    }
                    is TaskResult.Success -> {
                        // 继续执行
                    }
                }

                // 检查是否需要继续重复
                if (_currentExecutionCount.get() >= totalRepeatCount) {
                    break
                }

                // 任务间隔（可由子类重写）
                val interval = getRepeatInterval()
                if (interval > 0) {
                    delay(interval)
                }
            }

            _status = TaskStatus.COMPLETED
            TaskResult.Success

        } catch (e: CancellationException) {
            _status = TaskStatus.CANCELLED
            TaskResult.Cancelled
        } catch (e: Exception) {
            _status = TaskStatus.FAILED
            TaskResult.Failure(e)
        }
    }

    override fun cancel() {
        if (_status == TaskStatus.RUNNING) {
            _job?.cancel()
        }
        _status = TaskStatus.CANCELLED
    }

    override fun reset() {
        if (_status == TaskStatus.RUNNING) {
            cancel()
        }
        _currentExecutionCount.set(0)
        _status = TaskStatus.PENDING
    }

    /**
     * 子类需要实现的具体执行逻辑（异步网络请求）
     */
    protected abstract suspend fun doExecute(): TaskResult

    /**
     * 获取重复执行间隔（毫秒），默认无间隔
     * 子类可重写此方法来设置任务重复间隔
     */
    protected open fun getRepeatInterval(): Long = 0

    /**
     * 设置关联的Job，用于取消操作
     */
    protected fun setJob(job: Job) {
        _job = job
    }
}